package com.ruoyi.ade.llm.service.impl;

import com.ruoyi.ade.llm.agent.*;
import com.ruoyi.ade.llm.exception.AdeRecognizeException;
import com.ruoyi.ade.llm.model.Ade;
import com.ruoyi.ade.llm.model.ChatRequest;
import com.ruoyi.ade.llm.model.ChatResponse;
import com.ruoyi.ade.llm.service.IAdeService;
import com.ruoyi.ade.llm.utils.AdeDataProcessUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
@Slf4j
public class AdeServiceImpl implements IAdeService {


    @Override
    public List<Ade> recognize(String llmModel, String systemPrompt, String userPrompt, boolean afterFilter) {
        //Step 1:  判断是什么模型
        LLMAgent llmAgent = find(llmModel);

        //Step4: 大模型执行请求
        ChatRequest chatRequest = new ChatRequest(llmModel,systemPrompt,userPrompt);
        ChatResponse chatResponse = llmAgent.chat(chatRequest);
        String json = chatResponse.getMessage().getContent();
        //TODO 做个特殊处理， 识别结果超长的话 则认为无效了。
        if(json.length()>1024) {
            log.error("LLM:{}, 超长识别结果：{}", llmModel, json);
            json = "[]";
        }
        List<Ade> ades = AdeDataProcessUtils.getResult(json);

        //Step5: 判断是否启用后处理
        if(afterFilter)
            return AdeDataProcessUtils.filterAdes(ades);
        return ades;
    }


    /**
     * 根据模型名称 选择对应的执行Agent
     * @param model
     * @return
     */
    private LLMAgent find(String model){
        switch (model){
            case QianfanAgent.model_deepseek_v3:
            case QianfanAgent.model_ernie35_8k:
                return QianfanAgent.getInstance();
            case OllamaAgent.LLM_MODEL_QWEN2_7B:
            case OllamaAgent.LLM_MODEL_LLAMA31_8B:
            case OllamaAgent.LLM_MODEL_QWEN25_7B:
            case OllamaAgent.LLM_MODEL_QWEN25_14B:
                return OllamaAgent.getInstance();
            case  OpenAIAgent.model_gpt4o:
                return OpenAIAgent.getInstance();
            case DashScopeAgent.model_qwen_turbo:
                return DashScopeAgent.getInstance();
            default:
                throw new AdeRecognizeException("未知的大语言模型:"+model);
        }
    }
}
